check.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. """Validation of dependencies of packages
  2. """
  3. import logging
  4. from collections import namedtuple
  5. from pip._vendor.packaging.utils import canonicalize_name
  6. from pip._vendor.pkg_resources import RequirementParseError
  7. from pip._internal.distributions import (
  8. make_distribution_for_install_requirement,
  9. )
  10. from pip._internal.utils.misc import get_installed_distributions
  11. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  12. logger = logging.getLogger(__name__)
  13. if MYPY_CHECK_RUNNING:
  14. from pip._internal.req.req_install import InstallRequirement
  15. from typing import (
  16. Any, Callable, Dict, Optional, Set, Tuple, List
  17. )
  18. # Shorthands
  19. PackageSet = Dict[str, 'PackageDetails']
  20. Missing = Tuple[str, Any]
  21. Conflicting = Tuple[str, str, Any]
  22. MissingDict = Dict[str, List[Missing]]
  23. ConflictingDict = Dict[str, List[Conflicting]]
  24. CheckResult = Tuple[MissingDict, ConflictingDict]
  25. ConflictDetails = Tuple[PackageSet, CheckResult]
  26. PackageDetails = namedtuple('PackageDetails', ['version', 'requires'])
  27. def create_package_set_from_installed(**kwargs):
  28. # type: (**Any) -> Tuple[PackageSet, bool]
  29. """Converts a list of distributions into a PackageSet.
  30. """
  31. # Default to using all packages installed on the system
  32. if kwargs == {}:
  33. kwargs = {"local_only": False, "skip": ()}
  34. package_set = {}
  35. problems = False
  36. for dist in get_installed_distributions(**kwargs):
  37. name = canonicalize_name(dist.project_name)
  38. try:
  39. package_set[name] = PackageDetails(dist.version, dist.requires())
  40. except RequirementParseError as e:
  41. # Don't crash on broken metadata
  42. logger.warning("Error parsing requirements for %s: %s", name, e)
  43. problems = True
  44. return package_set, problems
  45. def check_package_set(package_set, should_ignore=None):
  46. # type: (PackageSet, Optional[Callable[[str], bool]]) -> CheckResult
  47. """Check if a package set is consistent
  48. If should_ignore is passed, it should be a callable that takes a
  49. package name and returns a boolean.
  50. """
  51. missing = {}
  52. conflicting = {}
  53. for package_name in package_set:
  54. # Info about dependencies of package_name
  55. missing_deps = set() # type: Set[Missing]
  56. conflicting_deps = set() # type: Set[Conflicting]
  57. if should_ignore and should_ignore(package_name):
  58. continue
  59. for req in package_set[package_name].requires:
  60. name = canonicalize_name(req.project_name) # type: str
  61. # Check if it's missing
  62. if name not in package_set:
  63. missed = True
  64. if req.marker is not None:
  65. missed = req.marker.evaluate()
  66. if missed:
  67. missing_deps.add((name, req))
  68. continue
  69. # Check if there's a conflict
  70. version = package_set[name].version # type: str
  71. if not req.specifier.contains(version, prereleases=True):
  72. conflicting_deps.add((name, version, req))
  73. if missing_deps:
  74. missing[package_name] = sorted(missing_deps, key=str)
  75. if conflicting_deps:
  76. conflicting[package_name] = sorted(conflicting_deps, key=str)
  77. return missing, conflicting
  78. def check_install_conflicts(to_install):
  79. # type: (List[InstallRequirement]) -> ConflictDetails
  80. """For checking if the dependency graph would be consistent after \
  81. installing given requirements
  82. """
  83. # Start from the current state
  84. package_set, _ = create_package_set_from_installed()
  85. # Install packages
  86. would_be_installed = _simulate_installation_of(to_install, package_set)
  87. # Only warn about directly-dependent packages; create a whitelist of them
  88. whitelist = _create_whitelist(would_be_installed, package_set)
  89. return (
  90. package_set,
  91. check_package_set(
  92. package_set, should_ignore=lambda name: name not in whitelist
  93. )
  94. )
  95. def _simulate_installation_of(to_install, package_set):
  96. # type: (List[InstallRequirement], PackageSet) -> Set[str]
  97. """Computes the version of packages after installing to_install.
  98. """
  99. # Keep track of packages that were installed
  100. installed = set()
  101. # Modify it as installing requirement_set would (assuming no errors)
  102. for inst_req in to_install:
  103. abstract_dist = make_distribution_for_install_requirement(inst_req)
  104. dist = abstract_dist.get_pkg_resources_distribution()
  105. assert dist is not None
  106. name = canonicalize_name(dist.key)
  107. package_set[name] = PackageDetails(dist.version, dist.requires())
  108. installed.add(name)
  109. return installed
  110. def _create_whitelist(would_be_installed, package_set):
  111. # type: (Set[str], PackageSet) -> Set[str]
  112. packages_affected = set(would_be_installed)
  113. for package_name in package_set:
  114. if package_name in packages_affected:
  115. continue
  116. for req in package_set[package_name].requires:
  117. if canonicalize_name(req.name) in packages_affected:
  118. packages_affected.add(package_name)
  119. break
  120. return packages_affected